<template>
  <scroll-view
    scroll-y
    class="w100p h100p"
    :scroll-top="scrollTop"
    :scroll-with-animation="false"
    show-scrollbar
    enable-back-to-top
    :refresher-enabled="!config.refreshOff"
    :refresher-default-style="isDark ? 'white' : 'black'"
    :refresher-triggered="triggered"
    @refresherrefresh="onRefresh"
    @scrolltolower="onReachBtm"
    @scroll="onScroll"
  >
    <list-index
      v-if="!(config.apiName && !list)"
      :config="config"
      :rows="list"
    />

    <view class="mt-3 ta-c">
      <view class="pt-8 ta-c" v-if="!list">
        <!-- <u-loading-icon /> -->
      </view>
      <view class="pt-8" v-else-if="!list.length">
        <q-empty text="暂无记录" height="66vh" />
      </view>
      <u-loading-icon v-else-if="loadMore" />
      <view v-else-if="noMore && total > 9" class="fz-14 op-5"
        >共{{ total }}条记录</view
      >
      <view class="pa-4"></view>
    </view>
  </scroll-view>
</template>

<script>
import { mapState } from "vuex";

export default {
  props: {
    config: Object,
    filterParams: Object,
    active: Boolean,
    index: Number,
  },
  computed: {
    ...mapState(["isDark"]),
    total() {
      return this.list?.length;
    },
  },
  data() {
    return {
      scrollTop: 0,
      list: null,
      triggered: false,
      page: 1,
      noMore: false,
      loadMore: false,
      storList: null,
      needRefresh: false,
    };
  },
  watch: {
    filterParams() {
      this.setRefresh();
    },
    active() {
      if (!this.list || this.needRefresh) {
        this.getList();
      }
    },
  },
  created() {
    this.getList();
    uni.$on("update-all-tab", ({ type, delay = 500 }) => {
      if (type && type != this.config.type) {
        return;
      }
      setTimeout(() => {
        this.setRefresh();
      }, delay);
    });
    uni.$on("update-one-tab", () => {
      this.getList();
    });
  },
  methods: {
    onScroll(e) {
      this.$emit("scroll", e);
    },
    setRefresh() {
      this.scrollTop = 0;
      this.needRefresh = true;
      this.getList();
    },
    async onRefresh() {
      await this.getList();
    },
    onReachBtm() {
      console.log("btm");
      this.getList(true);
    },
    async getList(more) {
      if (!this.active) {
        return;
      }
      let {
        apiName,
        tableName,
        params = {},
        pageSize = 10,
        noStore,
        checkUid,
      } = this.config;
      if (!apiName) return;
      let storeKey = `${apiName}-${this.index}`;
      if (noStore) {
        storeKey = null;
      }
      // const hasFilter = Object.keys(this.filterParams || {}).length > 0;
      // if (hasFilter) {
      //   storeKey = null;
      // }
      if (more) {
        if (this.loadMore || this.noMore) return;
        this.page += 1;
        this.loadMore = true;
      } else {
        if (this.triggered) return;
        this.page = 1;
        this.noMore = false;
        this.triggered = true;
      }
      try {
        params = {
          _limit: pageSize,
          _page: this.page,
          ...this.filterParams,
          ...params,
        };

        if (storeKey && this.page == 1) {
          if (!this.storList) {
            this.storList = await this.$h.getStorage(storeKey);
          }
          if (this.storList && tableName) {
            const { updateAt = 0, list } = this.storList;
            this.list = list.slice(0, params._limit);
            const {
              data: { time },
            } = await uni.$api.get(uni.$apiHub.checkRowUpdate, {
              params: {
                table: tableName,
                uid: checkUid,
              },
            });
            if (time > updateAt) {
              this.storList = null;
              this.starUpdateAt = time;
              await this.$setStorage(storeKey, null);
            }
          }
        }
        if (storeKey && this.storList) {
          if (this.page > 1) {
            await this.$sleep(100);
          }
          const { list, count } = this.storList;
          const len = this.page * params._limit;
          this.list = list.slice(0, len);
          console.log(storeKey, this.page, this.total);
          this.noMore = len >= count;
          // this.doEnd();
          // return;
        }
        this.needRefresh = false;
        const url = apiName;
        let {
          data: { items: rows, total: count },
        } = await uni.$api.get(url, {
          params,
        });
        // await this.$sleep(50);
        let list = this.list;
        this.noMore = rows.length < params._limit;
        if (more) {
          rows = rows.filter((row) => {
            return !list?.find((it) => it.id == row.id);
          });
          list = [...list, ...rows];
        } else {
          list = rows;
        }
        this.list = list;
        if (storeKey && this.noMore) {
          await this.$h.setStorage(storeKey, {
            count,
            list,
            updateAt: this.starUpdateAt || 0,
          });
        }
      } catch (error) {
        console.log(apiName, error);
      }
      this.doEnd();
    },
    doEnd() {
      this.triggered = false;
      this.loadMore = false;
    },
  },
};
</script>
